package src.DAO;
import src.jdbc.PostgreSQL;
import src.Entities.Pais;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author Patty
 */
public class PaisDAO {
    public String deletePais(int paisId){
        try {
            String sql = "DELETE FROM pais WHERE pais_id = ?;";
            PreparedStatement delete = PostgreSQL.getConnection().prepareStatement(sql);
            delete.setInt(1, paisId);
            return String.valueOf(delete.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public String insertPais(Pais pais) {
        try {
            String sql = "INSERT " +
                    "       INTO pais(pais_id, nombre, activo)" +
                    "     VALUES (NEXTVAL('pais_seq'), ?, ?, ?)";
            PreparedStatement insert = PostgreSQL.getConnection().prepareStatement(sql);
            insert.setInt(1, pais.getPaisId());
            insert.setString(2, pais.getNombre());
            insert.setString(3, String.valueOf(pais.getActivo()));
            return String.valueOf(insert.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public ArrayList selectPais(String sql) {
        ArrayList results = new ArrayList();
        try {
            Connection con = PostgreSQL.getConnection();
            Statement select = con.createStatement();
            ResultSet query = select.executeQuery(sql);
            while (query.next()) {
                Pais pais = new Pais(query.getInt("pais_id"),
                        query.getString("nombre"), query.getString("activo").charAt(0));
                results.add(pais);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return results;
    }

    public String updatePais(Pais pais) {
        try {
            String sql = "UPDATE pais" +
                    "        SET nombre= ?, activo = ?" +
                    "      WHERE pais_id = ?";
            PreparedStatement update = PostgreSQL.getConnection().prepareStatement(sql);
            update.setInt(1, pais.getPaisId());
            update.setString(2, pais.getNombre());
            update.setString(3, String.valueOf(pais.getActivo()));
            return String.valueOf(update.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }
}
